from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy import func
from database.connection import get_db
from models.email import Email

router = APIRouter()

@router.get("/length-distribution")
def get_length_distribution(db: Session = Depends(get_db)):
    try:
        # 计算每封邮件的内容长度并进行分组统计
        result = db.query(
            func.floor(func.length(Email.content) / 100) * 100,  # 按每100个字符分组
            func.count('*')
        ).filter(
            Email.isdeleted == False
        ).group_by(
            func.floor(func.length(Email.content) / 100) * 100
        ).all()
        
        # 处理统计结果
        distribution = {
            "ranges": [],
            "counts": []
        }
        
        for length_range, count in result:
            range_start = int(length_range)
            range_end = range_start + 100
            distribution["ranges"].append(f"{range_start}-{range_end}")
            distribution["counts"].append(count)
            
        return {
            "status": "success",
            "data": distribution
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"获取长度分布统计失败: {str(e)}"
        } 